package cn.xk.pet.service.impl;

import cn.xk.basic.exception.BusinessException;
import cn.xk.basic.service.IBaiduAiAuditService;
import cn.xk.basic.service.impl.BaseServiceImpl;
import cn.xk.basic.util.*;
import cn.xk.order.domain.OrderPetAcquisition;
import cn.xk.order.mapper.OrderPetAcquisitionMapper;
import cn.xk.org.domain.Employee;
import cn.xk.org.domain.Shop;
import cn.xk.org.mapper.EmployeeMapper;
import cn.xk.org.mapper.ShopMapper;
import cn.xk.pet.domain.SearchMasterMsg;
import cn.xk.pet.domain.SearchMasterMsgAuditLog;
import cn.xk.pet.dto.OrderDto;
import cn.xk.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.xk.pet.mapper.SearchMasterMsgMapper;
import cn.xk.pet.query.SearchMasterMsgQuery;
import cn.xk.pet.service.ISearchMasterMsgService;
import cn.xk.user.domain.Logininfo;
import cn.xk.user.domain.User;
import cn.xk.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        /*id    -   自增长
                title - 来自前端页面
        state          - 实体类默认值0
                name - 来自前端页面
        age - 来自前端页面
                gender - 来自前端页面
        coat_color - 来自前端页面
                resources - 来自前端页面 - 不做
        pet_type - 来自前端页面
                price - 来自前端页面
        address - 来自前端页面 - 优化 - 百度地图-输入提示
                user_id - request
        shop_id -   分配了最近店铺之后就可以添加了
                note - 备注*/
        //1.添加到数据库
        //1.1获取当前登录人信息
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);//自增id
        //2.百度AI智能审核
        Boolean boo1 = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean boo2 = baiduAiAuditService.imageAudit(msg.getResources());
        if (boo1 && boo2) {//审核通过
            msg.setState(1);
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核成功");
            //把日志添加到数据库
            searchMasterMsgAuditLogMapper.save(log);
            //获取离用户最近的店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop != null) {
                //找到最近的店铺
                msg.setShopId(nearestShop.getId());
                //发消息-店铺
                System.out.println("你有新的订单,请尽快去" + msg.getAddress() + "接回宠物");
            } else {//50公里内，没有找到最近的店铺
                msg.setState(3);//放到寻主池 - 1.没有最近的店铺  2.拒单
                System.out.println("你附近暂时没有店铺,请耐心等待!!!");
            }
            searchMasterMsgMapper.update(msg);
            return new AjaxResult();
        } else {//审核不通过
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //发消息-用户
            //SmsUtils.sendSms("寻主消息发布失败,请重新发布!!!");
            System.out.println("寻主消息发布失败,请修改之后重新发布!!!");
            //删除寻主消息
            searchMasterMsgMapper.del(msg.getId());
            return AjaxResult.me().setSuccess(false).setMsg("寻主消息发布失败,请修改之后重新发布!!!");
        }

    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户查询自己的寻主消息-设置User_id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询寻主池寻主消息
        query.setState(3);
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理寻主消息
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null) {//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(OrderDto orderDto) {
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(orderDto.getMsgId());
        if (order != null && order.getState() == 0) {
            //有订单,并且当前订单是待处理
            throw new BusinessException("订单正在处理,请不要重复接单");
        }
        //1.生产收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(orderDto.getMsgId());
        OrderPetAcquisition newOrder = createOrder(msg, orderDto);
        orderPetAcquisitionMapper.save(newOrder);
        if (order.getAddress() != null) {
            System.out.println("你有新的订单，请在2天内去" + order.getAddress() + "接回宠物");
        }
    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, OrderDto orderDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(orderDto.getNote());
        //3天之后没有接单就自动取消 - 定时器
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000));
        order.setPrice(msg.getPrice());
        //支付类型 - 确认订单才设置
        //宠物id - 确认订单，接回宠物再设置
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(orderDto.getHandler());
        order.setSearchMasterMsgId(orderDto.getMsgId());
        return order;
    }
}
